import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MenuServerByUDP {
	
	public static boolean isNonNegativeNumber(String s) {
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) < '0' || s.charAt(i) > '9') {
				return false;
			}
		}
		return true;
	}
	

	public static void main(String[] args) throws IOException {
		final String string = "MENU\n"
				+ "1.display nowtime\n"
				+ "2.display ip\n"
				+ "3.search file\n"
				+ "4.quit the menu\n";
		//201521123091
		try(DatagramSocket socket = new DatagramSocket(9999);){
            byte[] buf = new byte[1024];
            boolean done = false;
			while (!done) {
				DatagramPacket packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);
				String line = new String(packet.getData()).trim();
				for (int i = 0; i < buf.length; i++) {
					buf[i] = 0;
				}
				if (line.equals("quit")) {
					done = true;
				} else if (line.equals("menu")) {
					socket.send(new DatagramPacket(string.getBytes(), string.getBytes().length, packet.getAddress(), 8080));
					while (true) {
						socket.receive(packet);
						line = new String(packet.getData()).trim();
						for (int i = 0; i < buf.length; i++) {
							buf[i] = 0;
						}
						System.out.println(line);
						String output = null;
						if (isNonNegativeNumber(line)) {
							int num = Integer.parseInt(line);
							if (num == 1) {
								output = new SimpleDateFormat("yyyy-MM-dd HH:ss").format(new Date()) + "\n";
							} else if (num == 2) {
								output = packet.getAddress() + "\n";
							} else if (num == 3) {
								
							} else if (num == 4) {
								break;
							} else {
								output = "illegal input\n";
							}
						} else {
							output = "illegal input\n";
						}
						socket.send(new DatagramPacket(output.getBytes(), output.getBytes().length, packet.getAddress(), 8080));
						socket.send(new DatagramPacket(string.getBytes(), string.getBytes().length, packet.getAddress(), 8080));
					}
				} else {
					String output = "illegal input\n";
					socket.send(new DatagramPacket(output.getBytes(), output.getBytes().length, packet.getAddress(), 8080));
				}
			}
        } catch (SocketException e1) {
			e1.printStackTrace();
		}

	}

}
